<?php


namespace app\web\controller;


use app\common\lib\Jssdk;
use think\Controller;
use think\Env;

class Seven extends Controller
{
    protected $goddessNum = [
        1 => [1 => 4, 2 => 3,],
        2 => [1 => 5, 2 => 3,],
        3 => [1 => 5, 2 => 4,],
        4 => [1 => 4, 2 => 4,],
        5 => [1 => 4, 2 => 4,],
        6 => [1 => 4, 2 => 4,],
        7 => [1 => 4, 2 => 3,],
        8 => [1 => 5, 2 => 4,],
        9 => [1 => 4, 2 => 4,],
        10 => [1 => 5, 2 => 3,],
        11 => [1 => 2, 2 => 4,],
        12 => [1 => 3, 2 => 4,],
    ];


    public function index()
    {
//        $this->checkLogin();

        $signPackage = (new Jssdk())->getSignPackage();
        $this->assign('data', [
            'host' => $this->request->domain(),
            'ossHost' => Env::get('host.photo'),
            'title' => '当代单身狗恋爱观大揭秘',
            'share_title' => '当代单身狗恋爱观大揭秘', // 分享标题
            'share_introduction' => '准确率高达99%', // 分享描述
            'signPackage' => $signPackage
        ]);
        return $this->fetch();
    }

    /**
     * 检查session里是否有  unionid、headimgurl、name 这三个参数，如果为空，那么跳转到微信登录页面
     * @param $token
     */
    private function checkLogin()
    {
        if (empty(session('seven.headimgurl')) || empty(session('seven.nickname')))
        {
            $this->redirect('/web/seven/weixin_login');
        }
    }

    /**
     * 微信登陆
     */
    public function weixin_login()
    {
        $token = '123';
        $appid = config('wechat.mp_appid');
        $domain = Env::get('host.domain');
        $redirect_uri = urlencode($domain . '/web/seven/weixin_back');
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . $token . '#wechat_redirect');
        exit;
    }

    /**
     * 微信登陆返回
     */
    public function weixin_back()
    {
        $appid = config('wechat.mp_appid');
        $appsecret = config('wechat.mp_secret');

        $code = input('get.code');
        if (empty($code)) $this->error('微信授权失败！');

        $token = input('get.state');
        if (empty($token)) $this->error('获取token失败！');
        if (empty(session('seven.access_token')))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $access_token = json_decode(file_get_contents($access_token_url));
            if (isset($access_token->errcode))
            {
                $this->error('授权失败');
            }
            session('seven.access_token', $access_token->access_token);
            session('seven.refresh_token', $access_token->refresh_token);
            session('seven.openid', $access_token->openid);
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . session('seven.access_token') . '&openid=' . session('seven.openid') . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url));
        if (isset($user_info->errcode))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . session('seven.refresh_token');
            $access_token = json_decode(file_get_contents($access_token_url), true);
            if (!empty($access_token) && isset($access_token['access_token']) && isset($access_token['refresh_token']) && isset($access_token['openid']))
            {
                session('seven.access_token', $access_token['access_token']);
                session('seven.refresh_token', $access_token['refresh_token']);
                session('seven.openid', $access_token['openid']);

                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token['access_token'] . '&openid=' . $access_token['openid'] . '&lang=zh_CN';
                $user_info = json_decode(file_get_contents($user_info_url));
                if (isset($user_info->errcode))
                {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }
            } else
            {//失败的话，重新授权登录
                $this->redirect('/web/seven/weixin_login');
            }
        }
        //把微信返回的参数 保存到session里
        session('seven.nickname', $user_info->nickname);
        session('seven.sex', $user_info->sex);
        session('seven.city', $user_info->city);
        session('seven.province', $user_info->province);
        session('seven.country', $user_info->country);
        session('seven.headimgurl', $user_info->headimgurl);

        $this->redirect('/web/seven');
    }

    public function getReport()
    {
        $sex = htmlspecialchars(trim(input('get.sex/d')));
        $goddess = htmlspecialchars(trim(input('get.goddess/d')));
        return show(config('code.success'), '请求成功', [
            'num' => mt_rand(1, $this->goddessNum[$goddess][$sex]),
            'name' => session('seven.nickname')
        ]);
    }

    /**
     * 生成报告
     */
    public function report()
    {
        $name = htmlspecialchars(trim(input('get.name/s')));
        $num = htmlspecialchars(trim(input('get.num/d',1)));
        $sex = htmlspecialchars(trim(input('get.sex/d')));
        $goddess = htmlspecialchars(trim(input('get.goddess/d')));

        if (!in_array($goddess, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) || !in_array($sex, [1, 2]))
        {
            throw new \Exception('参数异常');
        }

        header("Content-type: image/png");

        if (mb_strlen($name) > 7)
        {
            $name = mb_substr($name, 0, 7) . '...';
        }

        $im = @imagecreatetruecolor(1500, 2668) or die("Cannot initialize new GD image stream");

        if ($sex == 1)
        {   // 男
            $bg_color = imagecolorallocate($im, 138, 205, 255); //138,205,255
            $name_color = imagecolorallocate($im, 73, 176, 229); //73,176,229
        } else
        {  // 女
            $bg_color = imagecolorallocate($im, 254, 149, 151); //254,149,151
            $name_color = imagecolorallocate($im, 255, 148, 151); //255,148,151
        }

        imagefilledrectangle($im, 0, 0, 1500, 2668, $bg_color);// 创建画布

        $im2 = imagecreatefromstring(file_get_contents("./static/seven/images/{$goddess}_{$sex}_{$num}.png"));
        imagecopy($im, $im2, 0, 0, 0, 0, imagesx($im2), imagesy($im2));
        $im3 = imagecreatefromstring(file_get_contents("./static/seven/images/sex{$sex}.png"));
        imagecopy($im, $im3, 0, 2360, 0, 0, imagesx($im3), imagesy($im3));

        imagettftext($im, 50, 0, 350, 850, $name_color, './static/seven/zk_font.ttf', $name);

        imagejpeg($im);
        imagedestroy($im);
        exit();
    }
}
